<template>
  <div>
    <!--顶部按钮-->
    <div style="margin-bottom: 18px; display: flex; justify-content: flex-end;">
      <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
      <el-button type="primary" @click="openAddMemberDialog">
        新增成员
      </el-button>
    </div>
    <!--表格-->
    <el-table 
      :data="memberData" 
      style="width: 100%; min-height: 520px; margin-top: 8px;" 
      border
      v-loading="loading"
      empty-text="暂无成员数据"
      :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 600 }"
      :cell-style="{ padding: '8px 0' }"
    >
      <el-table-column prop="id" label="用户编号" width="120" align="center" />
      <el-table-column prop="userName" label="用户名" width="160" align="center" />
      <el-table-column prop="userAccount" label="账号" width="170" align="center" />
      <el-table-column prop="major" label="专业" width="210" align="center" />
      <el-table-column prop="phoneNumber" label="手机号" width="210" align="center" />
      <el-table-column prop="userRole" label="身份" width="125" align="center">
        <template #default="{ row }">
          <el-tag v-if="row?.userRole" :type="getIdentityTagType(row.userRole)">
            {{ getIdentityText(row.userRole) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userAvatar" label="头像" width="120" align="center">
        <template #default="{ row }">
          <el-avatar
            v-if="row.userAvatar"
            :src="row.userAvatar"
            :size="40"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleRemove(row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="footer-container" style="position: static; margin-top: 16px; z-index: 10;">
      <div class="footer-left">
        <span class="data-count">共查询到 <b>{{ total }}</b> 条成员数据</span>
      </div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
        style="margin: 0; position: static;"
      />
    </div>
    <!-- 新增成员弹窗 -->
    <el-dialog
      v-model="showAddMemberDialog"
      title="新增活动成员"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="addMemberForm" label-width="80px">
        <el-form-item label="用户ID">
          <el-input v-model="addMemberForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddMemberDialog">取消</el-button>
        <el-button type="primary" @click="handleAddMemberSubmit" :loading="addMemberLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { listActivityMembersAPI, addActivityMemberAPI, deleteActivityMemberAPI } from "@/apis/activity";
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from 'xlsx';

// 导出为 Excel
const exportToExcel = () => {
  if (!memberData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", memberData.value);
  // 提取你想要导出的字段
  const exportData = memberData.value.map((item) => ({
    '用户ID': item.id,
    '用户名': item.userName,
    '用户账号':item.userAccount,
    '用户号码':item.phoneNumber
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};

const route = useRoute();
const memberData = ref<any[]>([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);

// 新增成员弹窗相关
const showAddMemberDialog = ref(false);
const addMemberForm = ref({
  userId: ""
});
const addMemberLoading = ref(false);

// 获取activityId
const activityId = computed(() => {
  const id = route.params.id;
  return typeof id === 'string' ? parseInt(id) : id;
});

// 加载成员数据
const loadMemberData = async () => {
  loading.value = true;
  try {
    const response = await listActivityMembersAPI({
      activityId: activityId.value,
      current: currentPage.value,
      pageSize: pageSize.value
    });
    if (response.code === 0 && response.data) {
      const records = Array.isArray(response.data.records) ? response.data.records : [];
      memberData.value = records.map((user: any) => ({
        id: user.id,
        userName: user.userName,
        userAccount: user.userAccount,
        userAvatar: user.userAvatar,
        userRole: user.userRole || "member",
        major: user.major || "未填写",
        phoneNumber: user.phoneNumber || "未填写",
        grade: user.grade || "未填写",
        userClass: user.userClass || "未填写"
      }));
      total.value = response.data.total || records.length;
    } else {
      memberData.value = [];
      total.value = 0;
    }
  } catch (error: any) {
    ElMessage.error('加载失败: ' + (error.message || error));
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadMemberData();
});

const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadMemberData();
};

const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadMemberData();
};

const getIdentityText = (identity: string) => {
  return identity === "manager" ? "负责人" : "普通成员";
};

const getIdentityTagType = (identity: string) => {
  return identity === "manager" ? "success" : "info";
};

// 移除成员
const handleRemove = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除成员「${row.userName}」吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    // 正确调用移除活动成员接口，传 userId 和 activityId
    const res = await deleteActivityMemberAPI({
      userId: row.id,
      activityId: activityId.value
    });
    if (res && res.code === 0) {
      ElMessage.success('移除成功');
      loadMemberData();
    } else {
      ElMessage.error('移除失败: ' + (res?.message || '未知错误'));
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败: ' + (error?.message || error));
    }
  }
};

// 打开新增成员弹窗
const openAddMemberDialog = () => {
  showAddMemberDialog.value = true;
};
// 关闭新增成员弹窗
const closeAddMemberDialog = () => {
  showAddMemberDialog.value = false;
};

// 新增成员
const handleAddMemberSubmit = async () => {
  if (!addMemberForm.value.userId) {
    ElMessage.warning("请输入用户ID");
    return;
  }
  addMemberLoading.value = true;
  try {
    const res = await addActivityMemberAPI({
      userId: Number(addMemberForm.value.userId),
      activityId: activityId.value
    });
    if (res && res.code === 0) {
      ElMessage.success("新增成员成功");
      showAddMemberDialog.value = false;
      addMemberForm.value.userId = "";
      loadMemberData();
    } else {
      ElMessage.error("新增成员失败: " + (res?.message || "未知错误"));
    }
  } catch (error: any) {
    ElMessage.error("新增成员失败: " + (error?.message || error));
  } finally {
    addMemberLoading.value = false;
  }
};
</script>

<style scoped>
.footer-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 0 8px;
  position: static;
  z-index: 10;
}
.footer-left {
  display: flex;
  align-items: center;
  font-size: 15px;
}
.data-count {
  margin-right: 10px;
}
.el-table{
  top: 0;
  background: #fff;
}
</style>